<template>
  <Card class="!m-10px">
    <p>角色名称：{{ role.roleName }}</p>
    <Tree
      v-if="permissionList.length"
      v-model:checkedKeys="checkedKeys"
      checkable
      checkStrictly
      :tree-data="permissionList"
      :field-names="fieldNames"
      :defaultExpandAll="true"
    />

    <Button type="primary" class="mt-20px mr-10px" @click="assignRole">确定</Button>
    <Button @click="emits('setIsShowRoleList', true)">取消</Button>
  </Card>
</template>

<script lang="ts">
  import { defineComponent } from 'vue';

  export default defineComponent({
    name: 'AssignRole',
  });
</script>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { Card, Tree, Button } from 'ant-design-vue';
  import type { TreeProps } from 'ant-design-vue';
  import { RoleModel } from '/@/api/acl/model/roleModel';
  import { PermissionListModel, PermissionModel } from '/@/api/acl/model/permissionModel';
  import { getPermissionListApi } from '/@/api/acl/permission';
  import { assignRoleApi, getAssignRoleApi } from '/@/api/acl/role';

  const props = defineProps<{
    role: RoleModel;
  }>();
  const emits = defineEmits(['setIsShowRoleList']);

  const fieldNames: TreeProps['fieldNames'] = {
    key: 'id',
    title: 'name',
  };

  interface CheckedKeys {
    checked: string[];
    halfChecked: string[];
  }

  const checkedKeys = ref<CheckedKeys>({
    checked: [],
    halfChecked: [],
  });
  const permissionList = ref<string[]>([]);

  // 过滤权限菜单空的children
  function filterEmptyChildren(permission) {
    if (permission.children && permission.children.length) {
      permission.children.forEach((cp) => filterEmptyChildren(cp));
    } else {
      permission.children = undefined;
    }
    return permission;
  }

  // 获取权限菜单列表
  const getPermissionList = async () => {
    const res = await getPermissionListApi();
    // 需要过滤掉4级菜单（按钮）的children属性
    const filterPermissionList = filterEmptyChildren(res);
    permissionList.value = filterPermissionList.children;
  };

  const getSelectedIds = (permission: PermissionModel) => {
    let ids: string[] = [];
    // 将里面select为true的对象上id收集到ids中
    if (permission.select) {
      ids.push(permission.id as string);
    } else {
      // 如果父级菜单没有选中，说明子菜单一定没有选中，不用遍历了
      return ids;
    }

    if (permission.children && permission.children.length) {
      permission.children.forEach((cp) => {
        const cIds = getSelectedIds(cp);
        ids = ids.concat(cIds);
      });
    }

    return ids;
  };

  onMounted(async () => {
    getPermissionList();
    const res = await getAssignRoleApi(props.role.id as string);
    // console.log(res);
    const ids = getSelectedIds((res.children as PermissionListModel)[0]);
    // console.log(ids);
    checkedKeys.value.checked = ids;
  });

  const assignRole = async () => {
    await assignRoleApi(props.role.id as string, checkedKeys.value.checked as string[]);
    emits('setIsShowRoleList', true);
  };
</script>
